import { useEffect, useState } from 'react'
import { Input, message, Select } from 'antd'
import Icon from '@ant-design/icons'

import { apiSetLastLegInformation } from '../../apis'
import { useBoundStore } from '../../store'
import { getLastTransportationTypeName, useUrlParams } from '../../utils'
import { CardHeaderEdit } from '../CardHeaderEdit'
import EditableForm from '../EditableForm'
import { FormSchemaItem } from '../EditableForm/interface'
import styles from './styles.module.less'

type TTransportType = 1 | 2 | 3

interface ILastInfoFormValues {
  lastMileTransportType?: TTransportType | null
  lastMileCarrier?: string | null
  lastMileWaybillNo?: string | null
}

// 运输方式类型守卫与转换（仅接受 1/2/3）
const toTransportType = (v: unknown): TTransportType | null =>
  v === 1 || v === 2 || v === 3 ? (v as TTransportType) : null

const formSchema: FormSchemaItem<ILastInfoFormValues>[] = [
  {
    name: 'icon',
    editable: false,
    span: ({ record }) => (record?.lastMileTransportType ? 2 : 0),
    hidden: record => !record?.lastMileTransportType,
    renderView: ({ record }) => {
      const type = record?.lastMileTransportType as TTransportType
      const TransportIcon = type ? getLastTransportationTypeName.iconMap[type] : undefined
      return TransportIcon ? <Icon component={TransportIcon} className={styles.icon} /> : null
    },
  },
  {
    label: '运输方式',
    name: 'lastMileTransportType',
    component: Select,
    span: ({ record }) => (record?.lastMileTransportType ? 10 : 12),
    componentProps: {
      allowClear: true,
      options: getLastTransportationTypeName.valueList.map(value => ({
        label: getLastTransportationTypeName(value),
        value,
      })),
    },
    renderView: ({ record }) => getLastTransportationTypeName(record?.lastMileTransportType),
  },
  {
    label: '承运商',
    name: 'lastMileCarrier',
    dependencies: ['lastMileTransportType'],
    component: ({ record, ...componentProps }) => {
      const lastMileTransportType = record?.lastMileTransportType
      if (lastMileTransportType === 1)
        return (
          <Select
            allowClear={true}
            options={['UPS', 'FedEx', 'DHL', 'USPS等'].map(item => ({ label: item, value: item }))}
            {...componentProps}
          />
        )
      return (
        <Input
          disabled={lastMileTransportType === 3}
          defaultValue={lastMileTransportType === 3 ? 'Amazon Freight' : ''}
          {...componentProps}
        />
      )
    },
  },
  {
    label: '运单号',
    name: 'lastMileWaybillNo',
    component: Input,
  },
]

export const LastInfo = () => {
  const [edit, setEdit] = useState(false)
  const [form] = EditableForm.useForm<ILastInfoFormValues>()
  const { waybillNo } = useUrlParams()
  const detail = useBoundStore(state => state.detail)

  const initForm = () => {
    form.setFieldsValue({
      lastMileTransportType: toTransportType(detail?.lastMileTransportType ?? null),
      lastMileCarrier: detail?.lastMileCarrier,
      lastMileWaybillNo: detail?.lastMileWaybillNo,
    })
  }

  const save = async () => {
    const { lastMileTransportType, lastMileCarrier, lastMileWaybillNo } = await form.getFieldsValue()
    if (!lastMileTransportType || !lastMileCarrier || !lastMileWaybillNo) {
      return message.error('请填写完整')
    }
    apiSetLastLegInformation({
      lastMileTransportType,
      lastMileCarrier,
      lastMileWaybillNo,
      waybillNo,
    })
      .then(() => {
        message.success('保存成功')
        useBoundStore.setState({
          detail: {
            ...detail,
            lastMileTransportType,
            lastMileCarrier,
            lastMileWaybillNo,
          },
        })
      })
      .finally(() => {
        setEdit(false)
      })
  }

  const onValuesChange = (changedValues: Partial<ILastInfoFormValues>) => {
    if (changedValues.lastMileTransportType) {
      form.setFieldsValue({ lastMileCarrier: changedValues.lastMileTransportType === 3 ? 'Amazon Freight' : '' })
    }
  }

  useEffect(() => {
    initForm()
  }, [detail])

  return (
    <>
      <CardHeaderEdit
        title="尾程信息"
        edit={edit}
        save={save}
        cancel={() => setEdit(false)}
        openEdit={() => setEdit(true)}
      />
      <EditableForm
        form={form}
        editable={edit}
        formSchema={formSchema}
        formProps={{
          layout: 'vertical',
          onValuesChange,
        }}
      />
    </>
  )
}
